package com.haoma.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haoma.entity.Category;
import com.haoma.exception.BlogException;
import com.haoma.mapper.CategoryMapper;
import com.haoma.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * Description:
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 分类的分页查询
     *
     * @param page
     * @param limit
     * @param name
     * @return
     */
    public IPage pageCategoryList(Long page, Long limit, String name) {
        // 设置分页参数
        Page<Category> categoryPage = new Page<>(page, limit);

        // 设置分页条件
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (name != null) {
            categoryLambdaQueryWrapper.like(Category::getName, name);
        }

        categoryLambdaQueryWrapper.orderByDesc(Category::getCreateTime);

        return categoryMapper.selectPage(categoryPage, categoryLambdaQueryWrapper);
    }

    /**
     * 删除分类
     *
     * @param id
     */
    public void delCategory(Integer id) {
        Category byId = getById(id);
        if (byId.getCount() >0) {
            throw new BlogException("该分类下还有数据");
        }
        categoryMapper.deleteById(id);
    }

    /**
     * 修改
     *
     * @param id
     * @param name
     */
    public void updateCategory(Integer id, String name) {
        Category categoryDb = getById(id);
        if (categoryDb == null) {
            throw new BlogException("修改失败");
        }
        categoryDb.setName(name);
        updateById(categoryDb);
    }

    /**
     * 保存
     *
     * @param name
     */
    public void saveCategory(String name) {
        if (!StringUtils.hasText(name)) {
            throw new BlogException("新增失败");
        }
        Category category = new Category();
        category.setName(name);
        categoryMapper.insert(category);
    }
}
